import Service from '../core/baseService';
import { deleteNullOrUndefinedField } from '../utils/index';

export default class OrderService extends Service {
  constructor(ctx) {
    super(ctx);
    this.model = ctx.sassmodel.Order;
  }

  async list(page = 1, pageSize = 20, query) {
    let total = 0;
    const queryParams = {
      where: deleteNullOrUndefinedField(query),
      include: [
        {
          model: this.ctx.model.OrderGoods,
        },
        {
          model: this.ctx.model.OrderAddress,
        },
      ],
      order: [['id', 'DESC']],
    };

    if (Object.keys(query).length === 0) {
      Object.assign(queryParams, {
        offset: (Number(page) - 1) * pageSize,
        limit: pageSize,
        distinct: true
      });
    }

    const result: any = await this.model.findAndCountAll(queryParams);
    return {
      list: result.rows,
      total: result?.count || total,
      page,
      pageSize,
    };
  }

  async detail(id) {
    const result = await this.model
      .findOne({
        where: {
          id
        },
        include: [
          {
            model: this.ctx.model.OrderAddress,
          },
          {
            model: this.ctx.model.OrderGoods,
          },
        ],
      });

    return result;
  }

  async update(id, data) {
    try {
      return await this.model
        .update(
          {
            ...data,
          },
          {
            where: {
              id
            }
          }
        )
    } catch (err: any) {
      this.ctx.logger.error(err.message);
      return '';
    }
  }


}
